<?php
namespace WDB\WebUI;
use WDB;

/**
 * Schema browser WebUIds
 * 
 * This WebUI class provides an interface for browsing tables, selecting one and then forwards requests
 * to the selected table. This basic implementation is connected directly to Analyzer\iSchema
 *
 * @author Richard Ejem <richard(at)ejem.cz>
 * @package WDB
 */
class Schema extends WDB\BaseObject
{
    /**@var WDB\Analyzer\iSchema*/
    protected $schemaAnalyzer;
    /**@var iTemplateAdapter*/
    protected $template;
    /**@var string name of default iTemplateAdapter object for WebUI templates*/
    protected $templateAdapterClass = '\\WDB\\WebUI\\SimpleTemplateAdapter';
    /**@var string template set identifier passed to template adapter*/
    protected $templateSet = 'default';
    
    /**@var iTable*/
    protected $selectedTable = NULL;
    
    /**@var iRequest*/
    protected $request;
    
    /**@var iTable[]*/
    protected $registeredTables = array();
    
    // <editor-fold defaultstate="collapsed" desc="constructor and factories">
    /**
     * Creates WebUI for schema analyzer.
     *
     * @param WDB\Analyzer\Schema schema analyzer
     * @return self 
     */
    public function __construct(WDB\Analyzer\Schema $schema)
    {
        $this->schemaAnalyzer = $schema;
        $this->template = new $this->templateAdapterClass($this->templateSet.'.schema');
        $this->template->schema = $this;
        $this->request = new HttpRequest($this->name);
        if (($selTable = $this->request->getSelectedTable()) !== NULL)
        {
            $this->selectTable($selTable);
        }
    }
    
    /**
     * Creates Schema webUI for specified schema in database
     *
     * @param string schema name
     * @param WDB\Database database connection where the schema is located
     * @return Schema
     */
    public static function forSchemaName($name, WDB\Database $database = NULL)
    {
        if ($database == NULL) $database = WDB\Database::getDefault();
        return new self($database->getSchema($name));
    }
    
    /**
     * Creates Schema webUI for currently selected schema in database
     *
     * @param WDB\Database database
     * @return Schema
     */
    public static function forCurrentSchema(WDB\Database $database = NULL)
    {
        return self::forSchemaName(NULL, $database);
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="Contained tables operations">
    /**
     * Registers WebUI iTable object which does not represent a table stored in database
     * so it is not accessible by Analyzer layer. If a table with given name is already
     * registered, it will be replaced with the table given to this method.
     *
     * @param iTable the table
     * @param string name identifier
     */
    public function registerTable(iTable $table, $name)
    {
        $this->registeredTables[$name] = $table;
    }
    
    /**
     * Returns all tables registered by registerTable method.
     *
     * @return iTable[]
     */
    public function getRegisteredTables()
    {
        return $this->registeredTables();
    }
    
    /**
     * Get all tables listed in schema admin
     *
     * @return Structure\TableLink[]
     */
    public function getTableSchemaList()
    {
        $result = array();
        foreach (array_merge($this->schemaAnalyzer->getTables(), $this->registeredTables) as $table)
        {
            if ($table->isListedInSchemaAdmin())
            {
                $result[] = new Structure\TableLink(array(
                    'name'=>$table->getName(),
                    'title'=>$table->getTitle(),
                ));
            }
        }
        return $result;
    }
    
    /**
     * Get currently selected table
     * 
     * @return iTable
     */
    public function getSelectedTable()
    {
        return $this->selectedTable;
    }
    
    /**
     * Sets ant initializes currently selected table. It is automatically done in constructor from iRequest.
     * 
     * @param string table name
     */
    protected function selectTable($tableName)
    {
        if ($tableName !== NULL)
        {
            $this->selectedTable = TableFactory::fromName($tableName, $this->schemaAnalyzer->getName(), $this->schemaAnalyzer->getDatabase());
            if (!$this->selectedTable->isWebUIAccessible())
            {
                $this->selectedTable = NULL;
                return null;
            }
            $this->selectedTable->setRequest($this->request);
            $this->selectedTable->handleRequest();
        }
        else
        {
            $this->selectedTable = NULL;
        }
    }
    // </editor-fold>
    
    /**
     * Get schema name
     *
     * @return string
     */
    public function getName()
    {
        return $this->schemaAnalyzer->name;
    }
    
        /**
     * Returns current request sent to this Schema object.
     *
     * @return iRequest
     */
    public function getRequest()
    {
        return $this->request;
    }
    
    // <editor-fold defaultstate="collapsed" desc="HTML generation">
    
    /**
     * Generates WebUI HTML and returns it as a string
     *
     * @return string
     */
    public function generateHTML()
    {
        return $this->template->parse();
    }
    
    /**
     * Generates WebUI HTML directly to output
     *
     * @return string
     */
    public function show()
    {
        return $this->template->show();
    }
    // </editor-fold>
}
